﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LinqToExcel;
using System.Runtime.Serialization;
using MensUnoShop.Models;

namespace MensUnoShop.Areas.Admin.Models
{
    public class ProductImport:MensUnoImport,IImport
    {
        public ProductImport(HttpPostedFileBase file, ImportType it) : base(file, it) { }
        public bool IMPORT(ref string result)
        {
            bool isok = false;
            long _markettagid;
            int _marketshowprice, _marketprice, _productcolortagid, _spectagid, _specstock;

            try
            {
                var execlFile = new ExcelQueryFactory(_filepath);
                execlFile.AddMapping<ProductData>(d => d.MarketSN, "貨號");
                execlFile.AddMapping<ProductData>(d => d.MarketTitle, "主標題");
                execlFile.AddMapping<ProductData>(d => d.MarketTagid, "次分類序號");
                execlFile.AddMapping<ProductData>(d => d.MarketShowprice, "市價");
                execlFile.AddMapping<ProductData>(d => d.MarketPrice, "售價");
                execlFile.AddMapping<ProductData>(d => d.MarketSdate, "開賣時間");
                execlFile.AddMapping<ProductData>(d => d.MarketEdate, "結束時間");
                execlFile.AddMapping<ProductData>(d => d.MarketSpec, "尺寸表");
                execlFile.AddMapping<ProductData>(d => d.MarketWashnote, "洗滌注意事項");
                execlFile.AddMapping<ProductData>(d => d.MarketShoppingnote, "購物須知");
                execlFile.AddMapping<ProductData>(d => d.MarketIntrodution, "商品說明");
                execlFile.AddMapping<ProductData>(d => d.MarketGrouptag, "系列標籤");
                execlFile.AddMapping<ProductData>(d => d.MarketColortag, "色彩標籤");
                execlFile.AddMapping<ProductData>(d => d.ProductBig, "子商品大圖400*400");
                execlFile.AddMapping<ProductData>(d => d.ProductSmall, "子商品小圖35*35");
                execlFile.AddMapping<ProductData>(d => d.ProductColorTag, "顏色");
                execlFile.AddMapping<ProductData>(d => d.ProductColorTagid, "顏色編號");
                execlFile.AddMapping<ProductData>(d => d.SpecTag, "尺寸");
                execlFile.AddMapping<ProductData>(d => d.SpecTagid, "尺寸編號");
                execlFile.AddMapping<ProductData>(d => d.SpecStock, "規格數量");

                var excel = execlFile.Worksheet<ProductData>("Product").ToList();
                var mksn = excel.Select(e => e.MarketSN).ToList().Distinct();
                foreach (var ssn in mksn)
                {
                    string sn = ssn.Trim();
                    //看這賣場存不存在
                    NormalMarket mk = MarketFactory.GetNormalMarket(sn);
                    if (mk == null)
                    {
                        var detail = excel.Where(d => d.MarketSN == ssn).ToList();
                        var mfirst = detail.FirstOrDefault();
                        //新增賣場Start-------------
                        //確認系列標籤
                        long grouptagid = TagFactory.CheckTag(mfirst.MarketGrouptag, Config.TagType.GROUP);
                        //確認色彩標籤
                        long colortagid = TagFactory.CheckTag(mfirst.MarketColortag, Config.TagType.COLORGOURP);

                        long.TryParse(mfirst.MarketTagid, out _markettagid);
                        int.TryParse(mfirst.MarketShowprice, out _marketshowprice);
                        int.TryParse(mfirst.MarketPrice, out _marketprice);


                        Guid mkguid = MarketFactory.CreateNewMarket(mfirst.MarketSN, mfirst.MarketTitle, _markettagid, _marketshowprice,
                                                                    _marketprice, mfirst.MarketSdate, mfirst.MarketEdate, mfirst.MarketWashnote,
                                                                    mfirst.MarketShoppingnote,mfirst.MarketSpec, mfirst.MarketIntrodution, grouptagid,
                                                                    colortagid);
                        //新增賣場End-------------
                        if (mkguid != Guid.Empty)
                        {
                            //新增商品Start-----------
                            var pd = detail.Select(p => new { p.ProductBig, p.ProductSmall, p.ProductColorTag, p.ProductColorTagid }).ToList().Distinct();
                            foreach (var p in pd)
                            {
                                int.TryParse(p.ProductColorTagid, out _productcolortagid);
                                long tagid = TagFactory.CheckTag(p.ProductColorTag, _productcolortagid, Config.TagType.PRODUCT);
                                Guid pdguid = MarketFactory.CreateNewProduct(mkguid, tagid, p.ProductBig, p.ProductSmall);
                                if (pdguid != Guid.Empty)
                                {
                                    var sp = detail.Where(d => d.MarketSN == sn && d.ProductColorTagid == p.ProductColorTagid).Select(s => new { s.SpecTag, s.SpecTagid, s.SpecStock });
                                    foreach (var s in sp)
                                    {
                                        int.TryParse(s.SpecTagid, out _spectagid);
                                        int.TryParse(s.SpecStock, out _specstock);
                                        long tagspid = TagFactory.CheckTag(s.SpecTag, _spectagid, Config.TagType.SPEC);
                                        MarketFactory.CreateNewSpec(pdguid, tagspid, _specstock);
                                    }
                                    //新增商品End-------------
                                    result = "Success(" + sn + ")";
                                    isok = true;
                                }
                                else
                                {
                                    _log.RecordExceptionFormat(_log.FlowLogPath, "[Product Create Fail("+sn+")]", p.ProductColorTagid+p.ProductColorTag);
                                    result = "Product Create Fail(" + sn + ")";
                                    isok = false;
                                }
                            }
                                                       
                        }
                        else
                        {
                            _log.RecordExceptionFormat(_log.FlowLogPath, "[Market Create Fail(" + sn + ")]","");
                            result = "Market Create Fail(" + sn + ")";
                            isok = false;
                        }
                    }
                    else
                    { 
                        //存在賣場就更新
                        var detail = excel.Where(d => d.MarketSN == ssn).ToList();
                        
                        var mfirst = detail.FirstOrDefault();
                        //更新賣場Start-------------
                        //確認系列標籤
                        long grouptagid = TagFactory.CheckTag(mfirst.MarketGrouptag, Config.TagType.GROUP);
                        //確認色彩標籤
                        long colortagid = TagFactory.CheckTag(mfirst.MarketColortag, Config.TagType.COLORGOURP);
                        

                        long.TryParse(mfirst.MarketTagid, out _markettagid);
                        int.TryParse(mfirst.MarketShowprice, out _marketshowprice);
                        int.TryParse(mfirst.MarketPrice, out _marketprice);

                        MarketFactory.UpdateMarket(mk.MKGUID, mfirst.MarketTitle, _markettagid, _marketshowprice,
                                                                    _marketprice, mfirst.MarketSdate, mfirst.MarketEdate, mfirst.MarketWashnote,
                                                                    mfirst.MarketShoppingnote, mfirst.MarketSpec, mfirst.MarketIntrodution, grouptagid,
                                                                    colortagid);
                        //更新賣場End-------------

                        var pd = detail.Select(p => new { p.ProductBig, p.ProductSmall, p.ProductColorTag, p.ProductColorTagid }).ToList().Distinct();
                        foreach (var p in pd)
                        {
                            int.TryParse(p.ProductColorTagid, out _productcolortagid);
                            long tagid = TagFactory.CheckTag(p.ProductColorTag, _productcolortagid, Config.TagType.PRODUCT);
                            var mkp = mk.PRODUCTLIST.FirstOrDefault(pp => pp.TITLETAGID == _productcolortagid);
                            if (mkp == null)
                            {
                                _log.RecordExceptionFormat(_log.FlowLogPath, "[新增商品]", _productcolortagid.ToString());
                                //商品不存在，新增
                                Guid pdguid = MarketFactory.CreateNewProduct(mk.MKGUID, tagid, p.ProductBig, p.ProductSmall);
                                if (pdguid != Guid.Empty)
                                {
                                    var sp = detail.Where(d => d.MarketSN == sn && d.ProductColorTagid == p.ProductColorTagid).Select(s => new { s.SpecTag, s.SpecTagid, s.SpecStock });
                                    foreach (var s in sp)
                                    {
                                        int.TryParse(s.SpecTagid, out _spectagid);
                                        int.TryParse(s.SpecStock, out _specstock);
                                        long tagspid = TagFactory.CheckTag(s.SpecTag, _spectagid, Config.TagType.SPEC);
                                        MarketFactory.CreateNewSpec(pdguid, tagspid, _specstock);
                                    }
                                    //新增商品End-------------
                                    result = "Success(" + sn + ")";
                                    isok = true;
                                }
                                else
                                {
                                    _log.RecordExceptionFormat(_log.FlowLogPath, "[Product Create Fail(" + sn + ")]", p.ProductColorTagid + p.ProductColorTag);
                                    result = "Product Create Fail(" + sn + ")";
                                    isok = false;
                                }
                            }
                            else
                            {
                                _log.RecordExceptionFormat(_log.FlowLogPath, "[更新商品]", mkp.TITLE+mkp.TITLETAGID);
                                //商品存在，更新
                                mkp.PICBIG = p.ProductBig;
                                mkp.PICSMALL = p.ProductSmall;
                                mkp.Update();
                                mkp.GetSpecification();
                                foreach (var sp in mkp.SPEC)
                                {
                                    foreach (var dp in detail)
                                    {
                                        int.TryParse(dp.ProductColorTagid, out _productcolortagid);
                                        int.TryParse(dp.SpecTagid, out _spectagid);
                                        int.TryParse(dp.SpecStock, out _specstock);
                                        if (_productcolortagid == mkp.TITLETAGID && _spectagid == sp.TITLETAGID)
                                        {
                                            sp.UpdateStock(_specstock);
                                        }
                                    }
                                }
                            }
                        }

                        result = "Success Update!!!";
                        isok = true;
                    }
                }
                
            }
            catch (Exception ex)
            {
                result = ex.ToString();
                isok = false;
            }
            return isok;
        }
    }

    [DataContract]
    public class ProductData
    {
        [DataMember(Order = 1)]
        public string MarketSN { set; get; }
        [DataMember(Order = 2)]
        public string MarketTitle { set; get; }
        [DataMember(Order = 3)]
        public string MarketTagid { set; get; }
        [DataMember(Order = 4)]
        public string MarketShowprice { set; get; }
        [DataMember(Order = 5)]
        public string MarketPrice { set; get; }
        [DataMember(Order = 6)]
        public string MarketSpec { set; get; }
        [DataMember(Order = 7)]
        public string MarketWashnote { set; get; }
        [DataMember(Order = 8)]
        public string MarketIntrodution { set; get; }
        [DataMember(Order = 9)]
        public string MarketGrouptag { set; get; }
        [DataMember(Order = 10)]
        public string MarketColortag { set; get; }
        [DataMember(Order = 11)]
        public string ProductBig { set; get; }
        [DataMember(Order = 12)]
        public string ProductSmall { set; get; }
        [DataMember(Order = 13)]
        public string ProductColorTag { set; get; }
        [DataMember(Order = 14)]
        public string ProductColorTagid { set; get; }
        [DataMember(Order = 15)]
        public string SpecTag { set; get; }
        [DataMember(Order = 16)]
        public string SpecTagid { set; get; }
        [DataMember(Order = 17)]
        public string SpecStock { set; get; }
        [DataMember(Order = 18)]
        public DateTime? MarketSdate { set; get; }
        [DataMember(Order = 19)]
        public DateTime? MarketEdate { set; get; }
        [DataMember(Order = 20)]
        public string MarketShoppingnote { set; get; }
    }

   
}